//
//  QDBusCodeManager.m
//  QDMetroClient
//
//  Created by YueWen on 2019/2/26.
//  Copyright © 2019 YueWen. All rights reserved.
//

#import "QDBusCodeManager.h"
#import "RITLQRCodeMaker.h"
#import "QDMetroClient-Swift.h"
#import "JX_GCDTimerManager.h"

/// 转公交码的ObjC方法
NSData *QDAsc2Bcd(NSData *asc, NSInteger r_align){

    //转成字节数组
    Byte *ascByte = (Byte *)[asc bytes];
    //字节个数
    NSInteger length = asc.length;
    //某个标志位
    int flag = ((length % 2) && r_align) ? 1 : 0;
    
    NSMutableData *resultData = [NSMutableData dataWithLength:(asc.length + 1)/2];

    // 结果
    Byte *resultBytes = (Byte *)[resultData bytes];

    //开始遍历所有的字节数组
    for (NSInteger i = 0; i < length; i++) {
        Byte b;
        Byte byte = ascByte[i];
        
        if (byte >= 'a') {
            b = byte - 'a' + 10;
        }else if (byte >= 'A'){
            b = byte - 'A' + 10;
        }else if (byte >= '0'){
            b = byte - '0';
        }else {
            b = 0;
        }
        
        if((i + flag) % 2){
            
            NSInteger index = (i + flag) / 2;
            Byte tempByte = resultBytes[index];
            tempByte = tempByte | (b & 0x0F);
            resultBytes[index] = tempByte;

        }else {
            
            NSInteger index = (i + flag) / 2;
            Byte tempByte = resultBytes[index];
            tempByte = tempByte | (b << 4);
            resultBytes[index] = tempByte;
        }
    }

    return [NSData dataWithBytes:resultBytes length:resultData.length];
}



@interface QDBusCodeManager()

@property (nonatomic, weak, readwrite)id<QDCodeDataManager>delegate;
/// 计时器
@property (nonatomic, strong, nullable) NSTimer *timer;
/// 付款类型
@property (nonatomic, copy) NSString *channel;
/// 是否存在支付方式
@property (nonatomic, assign) BOOL hasChannelTypes;

@end

@implementation QDBusCodeManager


#pragma mark - <QDCodeManager>

- (void)setCodeDelegate:(id<QDCodeDataManager>)codeDelegate {
    _delegate = codeDelegate;
}


- (id<QDCodeDataManager>)codeDelegate {
    return self.delegate;
}


- (void)setHasChannel:(BOOL)hasChannel {
    _hasChannelTypes = hasChannel;
}

- (BOOL)hasChannel {
    return self.hasChannelTypes;
}


- (void)setChannelType:(NSString *)channelType {
    _channel = channelType;
}


- (NSString *)channelType {
    return _channel;
}



- (void)becomeFirstControl {
    //开始进行网络请求
    [self cancleRequest];
    [self startRequestQRCode];
}

/// 开始请求二维码
- (void)startRequestQRCode {
    
    //开始请求
    [JX_GCDTimerManager.sharedInstance scheduledDispatchTimerWithName:@"QDBus" timeInterval:60 queue:dispatch_get_main_queue() repeats:true fireInstantly:true action:^{
        //开始请求
        [self requestBusCode];
    }];
}


// 取消请求
- (void)cancleRequest {
    [JX_GCDTimerManager.sharedInstance cancelTimerWithName:@"QDBus"];//取消
    NSLog(@"关闭公交二维码");
}



- (void)resignFirstControl {
    
    self.codeDelegate = nil;
    [self cancleRequest];
    
    NSLog(@"关闭公交二维码");
}

- (NSString *)title {
    return @"二维码对准扫码口扫码上车";
}


- (NSArray<NSString *> *)titles {
    return @[/*@"乘车码设置",*/@"使用范围"];
}

- (NSArray<NSString *> *)imageNames {
    return @[/*@"mc_pop_setting",*/@"mc_range"];
}


#pragma mark - 网络请求


- (void)reloadForce {
    [self cancleRequest];
    [self startRequestQRCode];
}


/// 请求公交二维码
- (void)requestBusCode {
    NSLog(@"请求公交二维码");
    
    if (!self.hasChannelTypes){
        [self.codeDelegate codeManager:self failType:QDMetroHeaderErrorTypeOutPayType]; return;
    }
    
    if (self.channel.isEmpty) {
        [self.codeDelegate codeManager:self failType:QDMetroHeaderErrorTypeOutDefaultChannel]; return;
    }
    
    [self requestBusCodeWithChannelType:self.channelType force:false complete:^(NSString * _Nonnull qrcode) {
        
        NSData *codeData = [qrcode dataUsingEncoding:NSUTF8StringEncoding];
        NSData *resultData = QDAsc2Bcd(codeData, 0);
        
        // 制作二维码
        [self.codeDelegate codeManager:self codeString:qrcode info:@{@"title": @"将二维码对准公交车载机扫描口刷码上车"} image:[RITLQRCodeMaker makeQRCodeWithData:resultData size:202]];
    }];
}


@end



